package bb.lanxing.lib.devices.igpsport;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.LongSparseArray;
//import com.alipay.sdk.data.a;
import com.garmin.fit.ActivityMesg;
import com.garmin.fit.DateTime;
import com.garmin.fit.Decode;
import com.garmin.fit.Event;
import com.garmin.fit.EventMesg;
import com.garmin.fit.EventType;
import com.garmin.fit.FileEncoder;
import com.garmin.fit.FileIdMesg;
import com.garmin.fit.FitRuntimeException;
import com.garmin.fit.Mesg;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.core.ble.AbsBleDevice;
import bb.lanxing.lib.devices.core.ble.BaseBluetoothGattCallback;
import bb.lanxing.lib.devices.utils.ByteUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class IGPSportDevice extends AbsBleDevice {
    public static final int IGS_COMPLETE = 1;
    public static final int IGS_FAILURE = 2;
    public static final int IGS_SUCCESS = 0;
    private static IGPSportDevice INSTANCE = null;
    public static final int OP_CHECK_TIME_OUT = 16;
    public static final int OP_DELETE_FIT = 7;
    public static final int OP_READ_FILES = 5;
    public static final int OP_READ_FIT = 6;
    public static final int OP_RECEIVED_DATA = 8;
    private final String CMD_DELETE_FIT;
    private final String CMD_READ_FILES;
    private final String CMD_READ_FIT;
    private final String CMD_ROOT_DIR;
    private final int IGSP_BLE_MTU;
    private final int IGS_DEFAULT_TIMEOUT;
    private final String IGS_FILE_LIST;
    private int mCmdCode;
    private long mCurrentFileId;
    private Decode mFitDecoder;
    private LongSparseArray<IGSPFile> mIGSFileMap;
    private BluetoothGattCharacteristic mIGSPWriter;
    private Set<IIGSPListener> mListenerSet;
    private String mWorkDir;
    private static final UUID IGSPROT_READER = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
    public static final UUID IGPS_SERVICE = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    private static final UUID IGSPROT_WRITER = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e");

    public interface IIGSPListener {
        void onProgressUpdate(int i);

        void onReadFiles(List<IGSPFile> list);

        void onReceivedData(int i, int i2, byte[] bArr);
    }

    public IGPSportDevice(Context context, SmartDevice smartDevice, String str) {
        super(smartDevice);
        this.CMD_READ_FILES = "a.f";
        this.CMD_READ_FIT = "b.f";
        this.CMD_DELETE_FIT = "c.f";
        this.IGS_FILE_LIST = "igs_files.fit";
        this.IGS_DEFAULT_TIMEOUT = 10;//a.a;
        this.IGSP_BLE_MTU = 20;
        this.mWorkDir = str;
        this.CMD_ROOT_DIR = str;
        init(context, smartDevice.getAddress(), new IGSportGattCallback(this));
    }

    public static IGPSportDevice getInstance() {
        return INSTANCE;
    }

    public void closeImmdately() {
        Handler handler = getHandler();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        close();
    }

    public static boolean isConnectedToDevice() {
        IGPSportDevice iGPSportDevice = INSTANCE;
        return iGPSportDevice != null && iGPSportDevice.isServicesDiscovered();
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onServicesDiscovered() {
        BluetoothGattService service = this.mBluetoothGatt.getService(IGPS_SERVICE);
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(IGSPROT_READER);
        BluetoothGattCharacteristic characteristic2 = service.getCharacteristic(IGSPROT_WRITER);
        this.mIGSPWriter = characteristic2;
        characteristic2.setWriteType(2);
        this.mBluetoothGatt.readCharacteristic(characteristic);
        setCharacteristicNotification(characteristic, true);
        readBattery();
        if (Build.VERSION.SDK_INT >= 21) {
            requestConnectionPriority(1);
        }
    }

    private void initDecoder() {
        if (this.mFitDecoder == null) {
            this.mFitDecoder = new Decode();
        }
        this.mFitDecoder.nextFile();
    }

    public boolean sendCmd(byte[] bArr, int i, int i2) {
        if (this.mBluetoothGatt == null || !isServicesDiscovered()) {
            e("Unable to send command to remote device");
            return false;
        }
        int i3 = Math.min(i2, 20);
        byte[] bArr2 = new byte[i3];
        System.arraycopy(bArr, i, bArr2, 0, i3);
        d("send data to device: " + ByteUtils.printlnByteArrayToUnsignHexString(bArr2));
        boolean execute = execute(AbsBleDevice.Request.newWriteRequest(this.mIGSPWriter, bArr2));
        return (!execute || i2 <= 20) ? execute : sendCmd(bArr, i + i3, i2 - i3);
    }

    private boolean sendFitFile(File file) {
        if (!file.exists()) {
            return false;
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bArr = new byte[1024];
            while (true) {
                int read = fileInputStream.read(bArr);
                if (read != -1) {
                    byteArrayOutputStream.write(bArr, 0, read);
                } else {
                    fileInputStream.close();
                    byte[] byteArray = byteArrayOutputStream.toByteArray();
                    d("send file to device: " + ByteUtils.printlnByteArrayToUnsignHexString(byteArray));
                    return sendCmd(byteArray, 0, byteArray.length);
                }
            }
        } catch (IOException e) {
            e(e);
            return false;
        }
    }

    public void sendTimeoutMessage(int i) {
        int i2 = i | 16;
        Handler handler = getHandler();
        handler.removeMessages(i2);
        handler.sendMessageDelayed(handler.obtainMessage(i2, i, i), 3500L);
    }

    public void removeTimeoutMessage(int i) {
        getHandler().removeMessages(i | 16);
    }

    public void readFileList() {
        if (!isServicesDiscovered()) {
            return;
        }
        getHandler().sendEmptyMessage(5);
    }

    private void _readFileList() {
        File file = new File(this.CMD_ROOT_DIR, "a.f");
        new File(this.CMD_ROOT_DIR, "igs_files.fit").delete();
        initDecoder();
        byte[] commandData = new GetHistoriesListCommand(file.getAbsolutePath()).getCommandData();
        sendCmd(commandData, 0, commandData.length);
        sendTimeoutMessage(5);
    }

    public void readFitFile(long j) {
        Handler handler = getHandler();
        handler.sendMessage(handler.obtainMessage(6, j));
    }

    private void _readFitFile(long j) {
        IGSPFile iGSPFile = this.mIGSFileMap.get(j);
        if (iGSPFile == null) {
            return;
        }
        byte[] commandData = new GetMultipleFitsCommand(new File(this.CMD_ROOT_DIR, "b.f")
                .getAbsolutePath(), Collections.singletonList(iGSPFile.localTimeStamp)).getCommandData();
        if (sendCmd(commandData, 0, commandData.length)) {
            this.mCurrentFileId = j;
        } else {
            this.mCurrentFileId = -1L;
        }
        sendTimeoutMessage(6);
    }

    public void deleteFile(int i, int i2) {
        if (!isServicesDiscovered()) {
            return;
        }
        Handler handler = getHandler();
        handler.sendMessage(handler.obtainMessage(7, i, i2));
    }

    private void _deleteFile(int i, int i2) {
        File file = new File(this.CMD_ROOT_DIR, "c.f");
        if (file.exists()) {
            file.delete();
        }
        FileEncoder fileEncoder = new FileEncoder(file);
        FileIdMesg fileIdMesg = new FileIdMesg();
        fileIdMesg.setType(com.garmin.fit.File.ACTIVITY_SUMMARY);
        fileIdMesg.setTimeCreated(new DateTime(0L));
        fileEncoder.write(fileIdMesg);
        EventMesg eventMesg = new EventMesg();
        eventMesg.setTimestamp(new DateTime(0L));
        eventMesg.setEvent(Event.USER_MARKER);
        eventMesg.setEventType(EventType.MARKER);
        fileEncoder.write(eventMesg);
        ActivityMesg activityMesg = new ActivityMesg();
        activityMesg.setTimestamp(new DateTime(i2));
        activityMesg.setLocalTimestamp((long) i);
        fileEncoder.close();
        sendFitFile(file);
    }

    private void _receivedData(byte[] bArr) {
        int i = this.mCmdCode;
        if (i == 5) {
            handleFileList(0, bArr);
        } else {
            dispatchData(0, i, bArr);
        }
    }

    private void handleFileList(int i, byte[] bArr) {
        if (bArr == null) {
            return;
        }
        File file = new File(this.CMD_ROOT_DIR, "igs_files.fit");
        try {
            int length = bArr.length;
            Decode.RETURN r4 = null;
            int i2 = 0;
            while (i2 < length && r4 != Decode.RETURN.END_OF_FILE) {
                int i3 = i2 + 1;
                r4 = this.mFitDecoder.read(bArr[i2]);
                if (r4 == Decode.RETURN.MESG) {
                    if (this.mIGSFileMap == null) {
                        this.mIGSFileMap = new LongSparseArray<>();
                    }
                    Mesg mesg = this.mFitDecoder.getMesg();
                    if (mesg.getNum() == 34) {
                        ActivityMesg activityMesg = new ActivityMesg(mesg);
                        IGSPFile iGSPFile = new IGSPFile();
                        iGSPFile.id = activityMesg.getTimestamp().getDate().getTime();
                        iGSPFile.localTimeStamp = activityMesg.getLocalTimestamp();
                        iGSPFile.size = activityMesg.getTotalTimerTime() * 1000.0f;
                        iGSPFile.timestamp = activityMesg.getTimestamp().getTimestamp();
                        this.mIGSFileMap.put(iGSPFile.id, iGSPFile);
                    }
                }
                i2 = i3;
            }
            if (r4 == Decode.RETURN.END_OF_FILE) {
                removeTimeoutMessage(this.mCmdCode);
                LinkedList linkedList = new LinkedList();
                for (int i4 = 0; i4 < this.mIGSFileMap.size(); i4++) {
                    linkedList.add(this.mIGSFileMap.get(this.mIGSFileMap.keyAt(i4)));
                }
                dispatchFiles(linkedList);
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);
            fileOutputStream.write(bArr);
            fileOutputStream.close();
        } catch (FitRuntimeException | IOException e) {
            dispatchFiles(null);
            file.delete();
            e(e);
        }
    }

    @Override
    public void handleMessage(Message message) {
        super.handleMessage(message);
        int i = message.what;
        if (i == 5) {
            _readFileList();
            this.mCmdCode = 5;
        } else if (i == 6) {
            _readFitFile((Long) message.obj);
            this.mCmdCode = 6;
        } else if (i == 7) {
            _deleteFile(message.arg1, message.arg2);
            this.mCmdCode = 7;
        } else if (i == 8) {
            _receivedData((byte[]) message.obj);
        } else if ((i & 16) == 16) {
            if (message.arg1 == 5) {
                dispatchFiles(null);
                return;
            }
            dispatchData(1, message.arg1, null);
            this.mIGSFileMap.get(this.mCurrentFileId).readBytes = 0L;
        }
    }

    private void dispatchFiles(List<IGSPFile> list) {
        Set<IIGSPListener> set = this.mListenerSet;
        if (set != null) {
            for (IIGSPListener iIGSPListener : set) {
                iIGSPListener.onReadFiles(list);
            }
        }
    }

    private void dispatchData(int i, int i2, byte[] bArr) {
        Set<IIGSPListener> set = this.mListenerSet;
        if (set != null) {
            for (IIGSPListener iIGSPListener : set) {
                iIGSPListener.onReceivedData(i, i2, bArr);
                if (bArr != null) {
                    IGSPFile iGSPFile = this.mIGSFileMap.get(this.mCurrentFileId);
                    IGSPFile.access$014(iGSPFile, bArr.length);
                    iIGSPListener.onProgressUpdate((int) ((((float) iGSPFile.readBytes) / iGSPFile.size) * 100.0f));
                }
            }
        }
    }

    public void registerIGSListener(IIGSPListener iIGSPListener) {
        if (this.mListenerSet == null) {
            this.mListenerSet = new HashSet();
        }
        this.mListenerSet.add(iIGSPListener);
    }

    public void removeIGSListener(IIGSPListener iIGSPListener) {
        Set<IIGSPListener> set = this.mListenerSet;
        if (set != null) {
            set.remove(iIGSPListener);
        }
    }

    static class IGSportGattCallback extends BaseBluetoothGattCallback<IGPSportDevice> {
        public IGSportGattCallback(IGPSportDevice iGPSportDevice) {
            super(iGPSportDevice);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
            super.onCharacteristicChanged(bluetoothGatt, bluetoothGattCharacteristic);
            Handler handler = ((IGPSportDevice) this.mClientRef).getHandler();
            if (IGPSportDevice.IGSPROT_READER.equals(bluetoothGattCharacteristic.getUuid())) {
                IGPSportDevice iGPSportDevice = (IGPSportDevice) this.mClientRef;
                iGPSportDevice.removeTimeoutMessage(iGPSportDevice.mCmdCode);
                handler.obtainMessage(8, bluetoothGattCharacteristic.getValue()).sendToTarget();
                iGPSportDevice.sendTimeoutMessage(iGPSportDevice.mCmdCode);
            }
        }
    }

    public static class IGSPFile {
        public long duration;
        public long id;
        public long localTimeStamp;
        public String name;
        private long readBytes;
        public float size;
        public long timestamp;

        static /* synthetic */ long access$014(IGSPFile iGSPFile, long j) {
            long j2 = iGSPFile.readBytes + j;
            iGSPFile.readBytes = j2;
            return j2;
        }
    }
}
